import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './stores'
import { useUserStore } from './stores/user'
import './style.css'

// 添加页面加载时的调试信息
console.log('=== 页面加载开始 ===')
console.log('当前存储状态:', {
  localStorageToken: localStorage.getItem('graduation_check_token'),
  localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
  sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
  sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info'),
  localStorageKeys: Object.keys(localStorage),
  sessionStorageKeys: Object.keys(sessionStorage)
})

// 监听所有可能清除存储的事件
const originalLocalStorageRemoveItem = localStorage.removeItem;
localStorage.removeItem = function(key) {
  console.log('localStorage.removeItem 被调用:', key)
  return originalLocalStorageRemoveItem.call(this, key)
}

const originalSessionStorageRemoveItem = sessionStorage.removeItem;
sessionStorage.removeItem = function(key) {
  console.log('sessionStorage.removeItem 被调用:', key)
  return originalSessionStorageRemoveItem.call(this, key)
}

const originalLocalStorageClear = localStorage.clear;
localStorage.clear = function() {
  console.log('localStorage.clear 被调用')
  return originalLocalStorageClear.call(this)
}

const originalSessionStorageClear = sessionStorage.clear;
sessionStorage.clear = function() {
  console.log('sessionStorage.clear 被调用')
  return originalSessionStorageClear.call(this)
}

// 添加一个定时器来检查存储状态的变化
setTimeout(() => {
  console.log('页面加载后1秒，当前存储状态:', {
    localStorageToken: localStorage.getItem('graduation_check_token'),
    localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
    sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
    sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
  })
}, 1000)

// 在应用初始化前尝试恢复用户状态
const storedToken = localStorage.getItem('graduation_check_token') || sessionStorage.getItem('graduation_check_token')
const storedUserInfo = localStorage.getItem('graduation_check_user_info') || sessionStorage.getItem('graduation_check_user_info')

if (storedToken && storedToken.length > 0 && storedUserInfo) {
  console.log('在应用初始化前检测到存储的登录信息，尝试恢复状态')
  try {
    // 这里我们暂时不直接操作store，因为pinia还未初始化
    console.log('存储的登录信息有效，将在应用初始化后恢复')
  } catch (e) {
    console.error('解析存储的登录信息失败:', e)
  }
}

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 使用插件 - 确保 Pinia 在路由之前初始化
app.use(pinia)  // 先初始化 Pinia

// 在Pinia初始化后，立即尝试恢复用户状态
console.log('Pinia已初始化')

// 获取用户store并尝试恢复状态
try {
  // 使用正确的方式获取userStore
  const userStore = useUserStore()
  console.log('获取到UserStore:', userStore)
  
  // 检查当前store状态
  console.log('UserStore当前状态:', {
    hasToken: !!userStore.token,
    tokenLength: userStore.token ? userStore.token.length : 0,
    hasUserInfo: !!userStore.userInfo,
    isLoggedIn: userStore.isLoggedIn
  })
  
  // 如果store中没有状态，但本地存储有，则强制恢复
  if (!userStore.isLoggedIn) {
    const storedToken = localStorage.getItem('graduation_check_token') || sessionStorage.getItem('graduation_check_token')
    const storedUserInfo = localStorage.getItem('graduation_check_user_info') || sessionStorage.getItem('graduation_check_user_info')
    
    console.log('检查本地存储状态:', {
      hasStoredToken: !!storedToken,
      storedTokenLength: storedToken ? storedToken.length : 0,
      hasStoredUserInfo: !!storedUserInfo
    })
    
    if (storedToken && storedToken.length > 0 && storedUserInfo) {
      console.log('尝试从本地存储恢复用户状态')
      const restored = userStore.forceRestoreState()
      console.log('恢复结果:', restored)
    }
  }
} catch (e) {
  console.error('获取或恢复UserStore时出错:', e)
}

app.use(router) // 再初始化路由
app.use(ElementPlus, {
  locale: zhCn,
})

// 添加应用挂载后的调试信息
app.config.globalProperties.$router = router
app.config.globalProperties.$pinia = pinia

// 添加页面刷新前的调试信息
window.addEventListener('beforeunload', () => {
  console.log('页面即将刷新/关闭，当前存储状态:', {
    localStorageToken: localStorage.getItem('graduation_check_token'),
    localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
    sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
    sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
  })
})

// 添加页面可见性变化的监听器
document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    console.log('页面隐藏，当前存储状态:', {
      localStorageToken: localStorage.getItem('graduation_check_token'),
      localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
      sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
      sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
    })
  } else {
    console.log('页面可见，当前存储状态:', {
      localStorageToken: localStorage.getItem('graduation_check_token'),
      localStorageUserInfo: localStorage.getItem('graduation_check_user_info'),
      sessionStorageToken: sessionStorage.getItem('graduation_check_token'),
      sessionStorageUserInfo: sessionStorage.getItem('graduation_check_user_info')
    })
  }
})

// 应用挂载完成后的回调
app.mount('#app')
console.log('应用已挂载')